//
//  ZPlayVideoViewController.m
//  DoctorFAQs
//
//  Created by zjq on 17/2/22.
//  Copyright © 2017年 zjq. All rights reserved.
//

#import "ZPlayVideoViewController.h"

#import "ZDoctorViewController.h"
#import "ZDVCommentViewController.h"

#import "ZVieoHeadView.h"
#import "ZVideoMidTableViewCell.h"
#import "ZDoctorHeadCell.h" // 用户评论
#import "ZCommentTableViewCell.h" //用户评论cell
#import "ZPostCommentView.h"


#import "ZPalyVModel.h"
#import "ZRecommendModel.h"
#import "TacticsDetailModel.h"
static NSString * const ZVideoMidTableViewCellIdentifier = @"ZVideoMidTableViewCellIdentifier";
static NSString * const ZPlayVideoDoctorHeadCellIdentifier = @"ZPlayVideoDoctorHeadCellIdentifier";
static NSString * const ZPlayVideoCommentTableViewCellIdentifier = @"ZPlayVideoCommentTableViewCellIdentifier";

@interface ZPlayVideoViewController ()<UITableViewDelegate,UITableViewDataSource,ZVieoHeadViewDelegate,UINavigationControllerDelegate>{
    
    UITableView * _mainTableView;
    LZUserInfo *userInfo;
    ZPostCommentView * _postView;
}
@property (nonatomic,strong) ZVieoHeadView * headView;
@property (nonatomic,strong) ZPalyVModel * playmodel;
@property (nonatomic,strong) NSMutableArray <ZRecommendModel *>* RecommendArray;
@property (nonatomic,strong) NSMutableArray <TacticsDetailModel *>* lzTacArray;
@end

@implementation ZPlayVideoViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.headView suspendVideo];
//    self.headView = nil;
//    [self.headView.playerView dealloc];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([userInfo.uid isEqualToString:@""] || userInfo.uid == nil) {
        [self remakeConstraints];
    }else {
        [self appearComment];
    }
}
// 修改tableView和评论栏的约束（游客模式）
- (void)remakeConstraints {
    [_mainTableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    _postView.hidden = YES;
}
// 登录模式显示评论栏
- (void)appearComment {
    _mainTableView.frame = CGRectMake(0, 0,SCREEN_Width, SCREEN_Height-129*ysIZE);
    _postView.hidden = NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialzeDatas];
    [self initlizeInterface];
//    [self PlayNetWorking];
}
- (void)initialzeDatas {
    self.RecommendArray = [@[] mutableCopy];
    self.lzTacArray = [@[] mutableCopy];
    userInfo = [LZUserInfo getUserInfo];
}
- (void)initlizeInterface {
    self.navigationItem.title = @"视频详情";
    self.view.backgroundColor = [UIColor whiteColor];
//    _mainTableView = [[UITableView alloc] initWithFrame:CGRectZero,  style:UITableViewStylePlain];
    _mainTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    self.navigationController.delegate = self;
    [_mainTableView registerClass:[ZDoctorHeadCell class] forCellReuseIdentifier:ZPlayVideoDoctorHeadCellIdentifier];
    [_mainTableView registerClass:[ZCommentTableViewCell class] forCellReuseIdentifier:ZPlayVideoCommentTableViewCellIdentifier];
    [_mainTableView registerClass:[ZVideoMidTableViewCell class] forCellReuseIdentifier:ZVideoMidTableViewCellIdentifier];
    [_mainTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"VideoNoting"];
   
    _mainTableView.tableHeaderView = self.headView;
    _mainTableView.separatorStyle = 0;
    
    //创建发布评论一栏
    _postView = [[ZPostCommentView alloc] init];
    [_postView.postBtn  addTarget:self action:@selector(postCommet) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_mainTableView];
    [self.view addSubview:_postView];
    [_postView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.bottom.equalTo(self.view);
        make.height.offset(45*ysIZE);
    }];
    
    [_mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.bottom.equalTo(_postView.mas_top);
    }];
    
    
    ESWeak(self, weakSelf);
    _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [weakSelf pullDownData];
        [weakSelf PlayNetWorking];
        [_mainTableView.mj_header endRefreshing];
    }];
    [_mainTableView.mj_header beginRefreshing];
}




// 表格视图协议
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    return _lzTacArray? _lzTacArray.count : 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 240*ysIZE;
    }else if (indexPath.section == 1 && indexPath.row == 0) {
        return 40*ysIZE;
    }else {
        return 85*ysIZE;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ESWeak(self, weakSelf);
    if (indexPath.section == 0) {
        ZVideoMidTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ZVideoMidTableViewCellIdentifier forIndexPath:indexPath];
        
        if (self.playmodel) {
            cell.zpModel = self.playmodel;
        }
        if (self.RecommendArray) {
            cell.recommendArray= self.RecommendArray;
        }
        cell.selcetVideoBlock = ^(NSInteger * row ,NSString * vid) {
            [weakSelf jumpLikeVideoWith:vid];
        };
        cell.selectionStyle = 0;
        return cell;
    }else if (indexPath.section == 1 && indexPath.row ==0) {
        ZDoctorHeadCell * cell = [tableView dequeueReusableCellWithIdentifier:ZPlayVideoDoctorHeadCellIdentifier forIndexPath:indexPath];
        cell.midTitleLabel.text = @"用户评论";
        cell.leftImageView.image = [UIImage imageNamed:@"voice_presentation"];
        cell.selectionStyle = 0;
        return cell;
    }else {
        ZCommentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ZPlayVideoCommentTableViewCellIdentifier forIndexPath:indexPath];
        cell.tacticsDetailModel = _lzTacArray[indexPath.row];
        cell.selectionStyle = 0;
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1 && indexPath.row ==0) {
        ZDVCommentViewController * vc = [[ZDVCommentViewController alloc] init];
        vc.vid = self.vid;
        vc.navigationItem.title = @"评论详情";
        [self.navigationController pushViewController:vc animated:YES ];
    }
}
// 相似视频的跳转
- (void)jumpLikeVideoWith:(NSString *)vid {
    ZPlayVideoViewController * zPlayVC = [[ZPlayVideoViewController alloc] init];
    zPlayVC.vid = vid;
    [self.navigationController pushViewController:zPlayVC animated:YES];
}

// 跳转医生界面
- (void)jionDotroVC {
    ZDoctorViewController * ZDVC = [[ZDoctorViewController alloc] init];
    ZDVC.did = _headView.zdModel.did;
    [self.navigationController pushViewController:ZDVC animated:YES];
}


- (void)PlayNetWorking {
    NSDictionary * dict = @{@"vid":self.vid};
    [YJProgressHUD showProgress:@"正在加载" inView:self.view];
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:dict paramarsSite:@"Consult/videoDetails" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([dict[@"code"] intValue] == 1 ) {
            [YJProgressHUD showMessage:@"加载成功" inView:self.view];
            [self hanldDataWithDict:dict[@"list"]];
        }else {
            [YJProgressHUD showMessage:@"加载失败" inView:self.view];
        }
        
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"网络请求出错" inView:self.view];
    }];
}

- (void)hanldDataWithDict:(NSDictionary * )dict {
    LZLog(@"7777%@",dict);
    ZDoctorTModel * dmodel = [[ZDoctorTModel alloc] initWithDict:[dict mutableCopy]];
    self.headView.zdModel = dmodel;
    self.headView.urlString = dict[@"url"];
    self.playmodel = [[ZPalyVModel alloc] initWithDict:dict];
    
    NSArray * videoArray = dict[@"video"];
    [self.RecommendArray removeAllObjects];
    for (NSMutableDictionary * vdict in videoArray) {
        ZRecommendModel * model = [[ZRecommendModel alloc] initWithDict:vdict];
        [self.RecommendArray addObject:model];
    }
    NSArray * cmtArray = dict[@"cmt"];
    [self.lzTacArray removeAllObjects];
    for (NSMutableDictionary * cmtDict in cmtArray) {
        TacticsDetailModel * model = [[TacticsDetailModel alloc] initWithDict:cmtDict];
        [self.lzTacArray addObject:model];
    }
    [_mainTableView reloadData];
    
}

-(ZVieoHeadView *)headView {
    if (_headView ) {
        return _headView;
    }
    _headView = [[ZVieoHeadView alloc] init];
    _headView.frame = CGRectMake(0, 0, SCREEN_Width, 276.5*ysIZE);
    _headView.ZVHDelegate = self;
    return _headView;
}

// 发布按钮的方法
- (void)postCommet {
    if ([_postView.commentField.text isEqualToString:@""]) {
        [YJProgressHUD showMessage:@"评论不可以为空~" inView:self.view];
        return;
    }
    // 引号转换
    NSString * comText = [_postView.commentField.text stringByReplacingOccurrencesOfString:@"\"" withString:@"”" ];
    
    
    if (!_vid || [_vid isEqualToString:@""]) {
        [YJProgressHUD showMessage:@"视频id不存在" inView:self.view];
        return;
    }
    
    NSDictionary *paramas = @{@"vid":_vid,@"uid":userInfo.uid,@"content":comText};
    
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Consult/addVideoCmt" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"-----视频评论数据----%@",dict);
        if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"评论成功" inView:self.view];
            // 评论textfield失去第一响应并且刷新数据
            _postView.commentField.text = @"";
            [_postView.commentField resignFirstResponder];
            [_mainTableView.mj_header beginRefreshing];
            
        }else if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"评论失败" inView:self.view];
        }
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"评论失败" inView:self.view];
    }];
    
}


// 下拉刷新
//- (void)pullDownData {

//}




@end
